import json
import re

with open('log3.txt', mode='r') as f:
    content = f.read()
    print(content)

# 使用正则表达式匹配所有的distance值
# distances = re.findall(r'"distance" : ([\d.]+),', content)

# 将所有的distance值累加计算得到结果
# total_distance = sum(float(distance) for distance in distances)

total_distance = 0
# 使用正则表达式提取时间戳和 JSON 数据
pattern = r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) :: (.*)'
matches = re.findall(pattern, content)

for match in matches:
    timestamp = match[0]
    json_str = match[1]

    # 解析 JSON 字符串
    try:
        json_data = json.loads(json_str)

        # 遍历每个元素，累加 distance 值
        for item in json_data:
            total_distance += item['distance']
            print(item['speed'])
    except ValueError:
        continue

print("总距离为:", total_distance)
